<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { Table, TableColumn } from '@/components/Table'
import { Dialog } from '@/components/Dialog'
import { Form, FormSchema } from '@/components/Form'
import { ElMessageBox, ElMessage } from 'element-plus'

import { ref, computed } from 'vue'
import { formatToDateTime } from '@/utils/dateUtil'
import { useTable } from '@/hooks/web/useTable'
import { useForm } from '@/hooks/web/useForm'
import { useValidator } from '@/hooks/web/useValidator'
import { getMenuListApi, updateMenuApi, deleteMenuApi } from '@/api/systemSettings/menuManage'
import { getAllButtonApi } from '@/api/systemSettings/buttonManage'
import { useUserStore } from '@/store/modules/user'
import { Icon } from '@/components/Icon'
import { BaseButton } from '@/components/Button'
import { pick } from 'lodash-es'

const buttonList = ref([])
const getAllButton = async () => {
  try {
    const { data } = await getAllButtonApi({ status: 1 })
    buttonList.value = data
  } catch (error) {
    console.log(error)
  }
}
getAllButton()

// Table
const columns: TableColumn[] = [
  {
    field: 'id',
    label: '序号',
    type: 'index',
    showOverflowTooltip: false,
    width: '80'
  },
  {
    field: 'title',
    label: '菜单名称',
    align: 'left'
  },
  {
    field: 'code',
    label: '菜单编码',
    align: 'left'
  },
  {
    field: 'path',
    label: '路由地址',
    align: 'left'
  },
  {
    field: 'component',
    label: '页面文件路径',
    align: 'left'
  },
  {
    field: 'icon',
    label: '菜单图标',
    slots: {
      default: ({ row }) => row.icon && <Icon icon={row.icon}></Icon>
    }
  },
  {
    field: 'sort',
    label: '排序'
  },
  {
    field: 'createTime',
    label: '创建时间',
    formatter: (row) => (row.createTime ? formatToDateTime(row.createTime) : '')
  },
  {
    field: 'hidden',
    label: '显示状态',
    formatter: (row) => (row.meta.hidden ? '隐藏' : '显示')
  },
  {
    field: 'action',
    label: '操作',
    width: 170,
    fixed: 'right',
    showOverflowTooltip: false,
    slots: {
      default: ({ row }) => (
        <div class="flex items-center gap-x-[10px]">
          <BaseButton type="primary" size="small" onClick={() => onOpenDialog(row)}>
            {{
              icon: () => <Icon size={20} icon="carbon:edit" />,
              default: () => '编辑'
            }}
          </BaseButton>
          <BaseButton class="!ml-0" type="danger" size="small" onClick={() => onDelete(row)}>
            {{
              icon: () => <Icon size={20} icon="material-symbols:delete-outline" />,
              default: () => '删除'
            }}
          </BaseButton>
        </div>
      )
    }
  }
]

const { tableMethods, tableState } = useTable({
  fetchDataApi: async () => {
    const userStore = useUserStore()
    const res = await getMenuListApi({
      roleId: userStore.getUserInfo?.roleId,
      tag: 0
    })
    return {
      list: res.data
    }
  }
})
const { loading, dataList } = tableState
const { refresh } = tableMethods

// Dialog
const visible = ref(false)
const isEdit = ref(false)
const title = computed(() => (isEdit.value ? '编辑' : '新增'))

// Form
const { formRegister, formMethods } = useForm()
const { getElFormExpose, setValues, getFormData } = formMethods

const { required } = useValidator()

const schema = computed<FormSchema[]>(() => [
  {
    field: 'parentId',
    label: '父级菜单',
    component: 'TreeSelect',
    componentProps: {
      renderAfterExpand: false,
      checkStrictly: true,
      checkOnClickNode: true,
      nodeKey: 'id',
      props: {
        label: 'name'
      },
      data: [
        {
          name: '根目录',
          id: 0
        },
        ...dataList.value
      ]
    },
    formItemProps: {
      rules: [required()]
    }
  },
  {
    field: 'name',
    label: '菜单名称',
    component: 'Input',
    formItemProps: {
      rules: [required()]
    }
  },
  {
    field: 'code',
    label: '菜单编码',
    component: 'Input',
    formItemProps: {
      rules: [required()]
    }
  },
  {
    field: 'path',
    label: '路由地址',
    component: 'Input',
    formItemProps: {
      rules: [required()]
    }
  },
  {
    field: 'component',
    label: '组件路径',
    component: 'Input'
  },
  {
    field: 'icon',
    label: '菜单图标',
    value: '',
    component: 'IconPicker'
  },
  {
    field: 'sort',
    label: '显示排序',
    value: 0,
    component: 'Input',
    componentProps: {
      type: 'number'
    },
    formItemProps: {
      rules: [required()]
    }
  },
  {
    field: 'buttonIds',
    label: '按钮权限',
    component: 'Select',
    componentProps: {
      multiple: true,
      collapseTags: true,
      collapseTagsTooltip: true,
      options: buttonList.value,
      props: {
        label: 'name',
        value: 'id'
      }
    }
  },
  {
    field: 'hidden',
    label: '是否隐藏',
    value: 0,
    component: 'RadioGroup',
    componentProps: {
      options: [
        {
          label: '是',
          value: 1
        },
        {
          label: '否',
          value: 0
        }
      ]
    }
  },
  {
    field: 'alwaysShow',
    label: '是否一直显示菜单',
    value: 0,
    component: 'RadioGroup',
    componentProps: {
      options: [
        {
          label: '是',
          value: 1
        },
        {
          label: '否',
          value: 0
        }
      ]
    }
  },
  {
    field: 'noCache',
    label: '是否缓存',
    value: 0,
    component: 'RadioGroup',
    componentProps: {
      options: [
        {
          label: '是',
          value: 0
        },
        {
          label: '否',
          value: 1
        }
      ]
    }
  },
  {
    field: 'breadcrumb',
    label: '是否显示面包屑',
    value: 1,
    component: 'RadioGroup',
    componentProps: {
      options: [
        {
          label: '是',
          value: 1
        },
        {
          label: '否',
          value: 0
        }
      ]
    }
  },
  {
    field: 'affix',
    label: '是否固定在标签页',
    value: 0,
    component: 'RadioGroup',
    componentProps: {
      options: [
        {
          label: '是',
          value: 1
        },
        {
          label: '否',
          value: 0
        }
      ]
    }
  },
  {
    field: 'noTagsView',
    label: '是否隐藏标签页',
    value: 0,
    component: 'RadioGroup',
    componentProps: {
      options: [
        {
          label: '是',
          value: 1
        },
        {
          label: '否',
          value: 0
        }
      ]
    }
  },
  {
    field: 'canTo',
    label: '是否可跳转',
    value: 0,
    component: 'RadioGroup',
    componentProps: {
      options: [
        {
          label: '是',
          value: 1
        },
        {
          label: '否',
          value: 0
        }
      ]
    }
  }
])

// 打开弹窗
const onOpenDialog = (row?) => {
  visible.value = true
  isEdit.value = !!row

  // 编辑
  if (row) {
    setValues({
      ...pick(row, [
        'id',
        'parentId',
        'name',
        'code',
        'path',
        'component',
        'icon',
        'sort',
        'hidden',
        'alwaysShow',
        'noCache',
        'breadcrumb',
        'affix',
        'noTagsView',
        'canTo'
      ]),
      buttonIds: row.buttonIds ? row.buttonIds.split(',').map((item) => Number(item)) : []
    })
  }
}

// 删除
const onDelete = async (row) => {
  ElMessageBox.confirm('是否删除该菜单?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      await deleteMenuApi({ menuId: row.id })
      ElMessage.success('操作成功！')
      refresh()
    })
    .catch(() => {})
}

// 重置
const onReset = async () => {
  const elFormExpose = await getElFormExpose()
  elFormExpose?.resetFields()
}

const disabled = ref(false)
//立即提交
// const onSubmit = async () => {
//   const formData = await getFormData(false)

//   updateMenuApi({
//     ...formData,
//     buttonIds: formData.buttonIds ? formData.buttonIds.join(',') : null
//   })
//     .then(() => {
//       visible.value = false
//       ElMessage.success('操作成功！')
//       refresh()
//     })
//     .catch((err) => {
//       console.log(err)
//     })
//     .finally(() => {
//       disabled.value = false
//     })
// }
</script>

<template>
  <ContentWrap title="菜单管理">
    <template #action>
      <BaseButton type="primary" @click="onOpenDialog">
        <template #icon>
          <Icon :size="20" icon="material-symbols:add" />
        </template>
        新增
      </BaseButton>
    </template>
    <Table :columns="columns" :data="dataList" :loading="loading" @refresh="refresh" />

    <!-- 新增/编辑-弹窗 -->
    <Dialog
      v-model="visible"
      :title="title"
      width="800"
      maxHeight="400px"
      :close-on-click-modal="false"
    >
      <Form
        class="ml-[auto] mr-[auto]"
        v-loading="disabled"
        :schema="schema"
        @register="formRegister"
      />
      <template #footer>
        <div class="text-center mb-[16px]">
          <BaseButton v-if="!isEdit" @click="onReset">重置</BaseButton>
          <BaseButton type="primary" :disabled="disabled" debounce @click="onSubmit"
            >立即提交</BaseButton
          >
        </div>
      </template>
    </Dialog>
  </ContentWrap>
</template>
@/api/system
